package cn.juc;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * 自定义不可重入锁
 */
@Slf4j
public class AgsTest {
    public static void main(String[] args) {
        MyLock lock=new MyLock();
        log.info("开始测试");
        new Thread(()->{
            //log.info("开始加锁了哦");
            try {

                lock.lock();//加锁
                //重复加锁测试
                lock.lock();
                log.info("加锁成功");
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
                lock.unlock();
            } finally {
                log.info("解锁成功");
                lock.unlock();
            }
        }).start();
        new Thread(()->{
            try {
                lock.lock();//加锁
                log.info("加锁成功");
              //  Thread.sleep(1000);
            } finally {
                log.info("解锁成功");
                lock.unlock();
            }
        }).start();

    }
}
class MyLock implements Lock{
    //独占锁
    class OwnerLock extends AbstractQueuedSynchronizer {
        @Override
        protected boolean tryAcquire(int arg) {
            if (compareAndSetState(0,1)){ //得到锁
                setExclusiveOwnerThread(Thread.currentThread()); //当前线程加锁
                return true;
            }
            return false;
        }
        @Override
        protected boolean tryRelease(int arg) {
           setExclusiveOwnerThread(null); //归还
            setState(0);
            return true;
        }

        @Override //判断是否持有独占
        protected boolean isHeldExclusively() {
            return getState()==1;
        }
        public Condition newCondition(){
            return new ConditionObject();
        }
    }
    private OwnerLock sync=new OwnerLock();
    @Override //加锁 失败进入队列
    public void lock() {
         sync.acquire(1);
    }

    @Override//加锁 可打断
    public void lockInterruptibly() throws InterruptedException {
        sync.acquireInterruptibly(1);
    }

    @Override //尝试一次加锁
    public boolean tryLock() {
        return sync.tryAcquire(1);
    }

    @Override //尝试一次加锁 可设置超时
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return sync.tryAcquireNanos(1,unit.toNanos(time));
    }

    @Override //解锁
    public void unlock() {
          sync.release(1);
    }

    @Override //变量
    public Condition newCondition() {
        return sync.newCondition();
    }
}
